package com.fzx.fzwsupplysystem.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.fzx.fzwsupplysystem.BuildConfig;
import com.fzx.fzwsupplysystem.MyApplication;
import com.fzx.fzwsupplysystem.R;
import com.fzx.fzwsupplysystem.bean.CardInfo;
import com.fzx.fzwsupplysystem.bean.PersonBean;
import com.fzx.fzwsupplysystem.util.AppConstant;
import com.fzx.fzwsupplysystem.util.CountTimes;
import com.fzx.fzwsupplysystem.util.JsonCallback;
import com.fzx.fzwsupplysystem.util.LogUtil;
import com.fzx.fzwsupplysystem.util.ToastUtil;
import com.fzx.fzwsupplysystem.view.CountTimeTextView;
import com.fzx.fzwsupplysystem.view.LoadingViewDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 类名：OtherCardActivity.java
 * 创建人：FangZhiXin
 * 时间：2019/11/18 17:18
 * 描述：其他证件类型
 */
public class OtherCardActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "OtherCardActivity";
    private CountTimeTextView tv_count;
    private Spinner sp_card_type;
    private ArrayAdapter<String> spAdapter;
    private List<String> spList;
    private EditText et_card_num;
    private Button btn_submit;
    private Button btn_cancel;

    private int mCardType = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_card);
        loadingViewDialog = new LoadingViewDialog(this);
        initView();
        initSpinner();
//        showLoadingDialog();
    }

    private void initView() {
        tv_count = findViewById(R.id.tv_count);
        sp_card_type = findViewById(R.id.sp_card_type);
        et_card_num = findViewById(R.id.et_card_num);
        btn_submit = findViewById(R.id.btn_submit);
        btn_cancel = findViewById(R.id.btn_cancel);
        et_card_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv_count.resetTime();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_card_num.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String s = et_card_num.getText().toString();
                if (!"".equals(s)) {
                    //进入下页
                    requestPersonStatus();
                }
                return false;
            }
        });
        btn_submit.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
    }

    private void initSpinner() {
        spList = new ArrayList<>();
        spList.add("--证件类型 ID Type--");
        spList.add("护照 Passport");
        spList.add("回乡证 Home Return Permit");
        spList.add("台胞证 MTPs");
        spAdapter = new ArrayAdapter<String>(this, R.layout.item_spinner_card_type_layout, R.id.tv_text, spList);
        sp_card_type.setAdapter(spAdapter);
        sp_card_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mCardType = position;
                if (position == 0) {
                    et_card_num.setEnabled(false);
                    et_card_num.setText("");
                } else {
                    et_card_num.setEnabled(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                mCardType = 0;
                et_card_num.setEnabled(false);
            }
        });
        sp_card_type.setSelection(0);
    }

    private LoadingViewDialog loadingViewDialog;

    private void showLoadingDialog() {
        hideLoadingDialog();
        loadingViewDialog.show();
    }

    private void showLoadingDialog(String note) {
        hideLoadingDialog();
        loadingViewDialog.setTextLoad(note);
        loadingViewDialog.show();
    }

    private void hideLoadingDialog() {
        if (loadingViewDialog != null && loadingViewDialog.isShowing()) {
            loadingViewDialog.dismiss();
        }
    }

    private void startTimeDown() {
        tv_count.startTimeDown(AppConstant.CountTime, 1, new CountTimes.OnCountTimeListener() {
            @Override
            public void onStart(int time) {
                tv_count.setText("" + time);
            }

            @Override
            public void onTick(int time) {
                tv_count.setText("" + time);
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFinish(int time) {
                gotoHome();
            }
        });
    }

    private void releaseTimeDown() {
        tv_count.release();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        tv_count.resetTime();
        hideSoftInput(getCurrentFocus(), this);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startTimeDown();
    }

    @Override
    protected void onStop() {
        super.onStop();
        releaseTimeDown();
    }

    public void OnBack(View view) {
        gotoHome();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                requestPersonStatus();
                break;
            case R.id.btn_cancel:
                finishAc();
                break;
        }
    }

    /**
     * 请求人员信息
     */
    private void requestPersonStatus() {
        if (mCardType == 0) {
            ToastUtil.showToast(getApplicationContext(), "请选择证件类型");
            return;
        }
        String string = et_card_num.getText().toString();
        if ("".equals(string)) {
            ToastUtil.showToast(getApplicationContext(), "请输入证件号");
            return;
        }
        AppConstant.cardId = string.trim();
        if (MyApplication.isDebug) {
            //调试模式使用测试数据
            AppConstant.cardId = AppConstant.DEFAULT_ID;
        }
        showProgressDialog(false, "正在加载，请稍后");
        OkGo.<PersonBean>get(AppConstant.URL_PERSON_INFO).tag(this)
                .params("idCard", AppConstant.cardId)//证件号
                .params("matchId", AppConstant.matchId)//赛事id
                .execute(new JsonCallback<PersonBean>(PersonBean.class) {
                    @Override
                    public void onSuccess(Response<PersonBean> response) {
                        if (response == null) {
                            showMessageDialog("提示", "请求失败，请联系管理人员", false, true);
                            return;
                        }
                        PersonBean personBean = response.body();
                        if (personBean == null) {
                            showMessageDialog("提示", "数据异常，请联系管理人员", false, true);
                            return;
                        }
                        Log.i(TAG, "onSuccess: " + personBean.toString());
                        String code = personBean.getCode();
                        if ("000000".equals(code)) {
                            //这里判断是否是已在数据库中的身份证号，是的话弹框提示并退出
                            if (!MyApplication.isDebug) {
                                String idType = personBean.getIdType();
                                Log.i(TAG, "onSuccess: idType" + idType);
                                if ("身份证".equals(idType)) {
                                    showYNDialog("您输入的是身份证号码，请直接刷身份证进行领物", "确定", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            gotoHome();
                                        }
                                    }, "取消", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    });
                                    return;
                                }
                            }
                            //正常有数据
                            String status = personBean.getStatus();
                            if ("0".equals(status)) {//未领取 0
                                //未领取，进入人工检查页面
                                Intent intent = new Intent(OtherCardActivity.this, CardCheckActivity.class);
                                intent.putExtra("PersonBean", (Serializable) personBean);
                                startActivity(intent);
                                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                            } else if ("1".equals(status)) {//已领取 1
                                showMessageDialog("提示", "您已打印过领物单，请勿重复打印，谢谢！", false, true);
                            }
                        } else {
                            showMessageDialog("温馨提示", "抱歉，没有您的参赛信息，如有疑问，请联系现场工作人员！", false, false);
                        }
                    }

                    @Override
                    public void onError(Response<PersonBean> response) {
                        LogUtil.i(TAG, "onError: " + response.getException());
                        showMessageDialog("提示", "网络异常，请联系管理人员", false, true);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        hideProgressDialog();
                    }
                });
    }

}
